/**
 /**
 * Created by tdzl2003 on 8/24/16.
 */
import React from 'react';
import {Popconfirm, Button, Menu, Dropdown, Icon, message, Select} from 'antd';

import {get, $delete, put} from '../../logics/rpc';
import ObjectTable from '../../components/ObjectTable';
import AntdSelect from '../../components/AntdSelect';
import alert from '../../utils/alert';
import SetPwdModal from './SetPwdModal';
import AddAccModal from './AddAccModal';
import md5 from '../../logics/md5';
const Option = Select.Option;
export default class List extends React.Component {
  state = {
    setPwdModalVisible: false,
    addAccModalVisible: false,
    roleList: [],
  };

  async componentWillMount() {
    //获取角色
    const fetchRoleData = (params) => get('/admin/role/list?page=0&pageSize=1', params);
    try {
      const {data, totalCount} = await fetchRoleData({});
      this.setState({
        roleList: data
      });
    } catch (err) {
      console.log("获取权限错误", err);
    }
  }
  fetchData = (params) => {
    const ret = get('/admin/acc/list', params);
    ret.then(function(res) {
      const dataArr = res.data;
      for(let i=0;i<dataArr.length;i++){
        if(!dataArr[i].role){
          dataArr[i].role={id:0,name:''}
        }
     }
    });
    return ret;
  };
  columns = [{
    title: 'ID',
    dataIndex: 'id',
    width: 60,
  }, {
    title: '账号名',
    dataIndex: 'account',
    width: 120,

  }, {
    title: '角色',
    width: 240,
    render: (acc, value)=>(
      <div>
        <AntdSelect
          dataSource={this.state.roleList}
          defaultValue={acc.role.name}
          style={{width: 120}}
          onChange={(value) => this.setRole(acc, value)}
        />
      </div>
    )
  }, {
    title: '操作',
    render: acc => (
      <div>
        <Popconfirm placement="topRight" title={`确认删除账号${acc.account}吗？`} onConfirm={()=>this.deleteAcc(acc)}>
          <Button size="small">删除</Button>
        </Popconfirm>
        <Button size="small" onClick={()=>this.setPwd(acc)}>修改密码</Button>
      </div>
    ),
  }];


  //设置角色权限
  setRole = async(acc, value) => {
    try {
      await put(`/admin/acc/${acc.id}/role`, {
        value: value
      });
      alert('设置成功');
    } catch (err) {
      alert("设置失败");
      console.log("设置失败", err);
    }


  };
  //删除管理员
  async deleteAcc(acc) {
    try {
      await $delete(`/admin/acc/${acc.id}`);
      this.refs.table.removeItem(acc);
    } catch (err) {
      switch (err.code) {
        case 409:
          alert('您不能删除您自己！');
          break;
        default:
          alert('删除失败');
          break;
      }
    }
  };

  setPwd(acc) {
    this.setState({
      setPwdModalVisible: true,
      acc: acc,
    });
  };

  dismissSetPwd = () => {
    this.setState({
      setPwdModalVisible: false,
    })
  };
  onSubmitSetPwd = async({newPwd}) => {
    const {acc} = this.state;
    try {
      await put(`/admin/acc/${acc.id}/pwd`, {
        newPwd: md5(newPwd),
      });
      alert('修改成功');
    } catch (err) {
      alert('修改失败');
    }
  };
  showAddAcc = () => {
    this.setState({
      addAccModalVisible: true,
    });
  };
  dismissAddAcc = () => {
    this.setState({
      addAccModalVisible: false,
    });
  };
  renderHeader = () => {
    return (
      <div>
        <Button onClick={this.showAddAcc}>添加管理员账号</Button>
      </div>
    );
  };
  onAccAdded = () => {
    this.refs.table.refresh();
  };

  render() {
    const {setPwdModalVisible, addAccModalVisible} = this.state;
    return (
      <div>
        <ObjectTable
            columns={this.columns}
            fetchData={this.fetchData}
            ref="table"
            title={this.renderHeader}
        />
        <SetPwdModal
          visible={setPwdModalVisible}
          dismiss={this.dismissSetPwd}
          onSubmit={this.onSubmitSetPwd}
        />
        <AddAccModal
          visible={addAccModalVisible}
          dismiss={this.dismissAddAcc}
          onAdded={this.onAccAdded}
        />
      </div>
    );
  }
}
